package com.wanjia.seal.manager.controller;

import com.alibaba.fastjson.JSONObject;
import com.wanjia.seal.manager.annotation.LoginToken;
import com.wanjia.seal.manager.entity.*;
import com.wanjia.seal.manager.mapper.SysMenuMapper;
import com.wanjia.seal.manager.mapper.SysRoleMenuMapper;
import com.wanjia.seal.manager.mapper.SysUserRoleMapper;
import com.wanjia.seal.manager.utils.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/api")
@Api(tags = "获取权限")
@Slf4j
public class UserPermissionController extends BaseController{

    @Resource
    SysUserRoleMapper sysUserRoleMapper;
    @Resource
    SysRoleMenuMapper sysRoleMenuMapper;
    @Resource
    SysMenuMapper sysMenuMapper;

    @ResponseBody
    @GetMapping("/userpermission")
    @ApiOperation(value = "查询用户菜单权限", notes = "查询是否成功")
    @LoginToken
    public JsonResult<SysMenuVO> GetUserPermission(Integer UserId){
        HashSet<SysMenu> sysMenusSet = new HashSet<>();
        List<SysUserRole> roleIdByUserId = sysUserRoleMapper.getRoleIdByUserId(UserId);
        for (SysUserRole sysUserRole : roleIdByUserId) {
            List<SysRoleMenu> roleMenuByRoleId = sysRoleMenuMapper.getRoleMenuByRoleId(sysUserRole.getRoleId());
            for (SysRoleMenu sysRoleMenu : roleMenuByRoleId) {
                Integer menuId = sysRoleMenu.getMenuId();
                List<SysMenu> menuByMenuId = sysMenuMapper.getMenuByMenuId(menuId);
                for (SysMenu sysMenu : menuByMenuId) {
                    sysMenusSet.add(sysMenu);
                }
            }
        }
        LinkedHashSet<SysMenu> sortedSet = sysMenusSet.stream().sorted(Comparator.comparing(SysMenu::getMenuId)).collect(Collectors.toCollection(LinkedHashSet::new));
        SysMenuVO sysMenuA =new SysMenuVO();
        sysMenuA.setPermissions(sortedSet);
        System.out.println(sysMenuA);
        return new JsonResult<>(OK,sysMenuA);
    }
}
